package com.codebox.knowledge.collapsingtoolbar;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

import com.codebox.common.util.LogUtils;
import com.codebox.common.util.RxBus;

/**
 * @author Able
 * @date 2019/5/17
 */
public class TransferHeaderBehavior extends CoordinatorLayout.Behavior<RelativeLayout> {

    private float deltaY;

    /**
     * 处于中心时候原始X轴
     */
    private int mOriginalHeaderX = 0;
    /**
     * 处于中心时候原始Y轴
     */
    private int mOriginalHeaderY = 0;


    public TransferHeaderBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, RelativeLayout child, View dependency) {
        return dependency instanceof Toolbar;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, RelativeLayout child, View dependency) {

//        LogUtils.e("init dependency " + dependency.getWidth() + " , " + dependency.getHeight());
//        LogUtils.e("init child " + child.getWidth() + " , " + child.getHeight());

        // 计算X轴坐标
        if (mOriginalHeaderX == 0) {
            this.mOriginalHeaderX = child.getWidth();
        }
        // 计算Y轴坐标
        if (mOriginalHeaderY == 0) {
//            mOriginalHeaderY = dependency.getHeight() - child.getHeight();
            mOriginalHeaderY = dependency.getHeight() + child.getHeight();
        }

//        LogUtils.e("Original X,Y >> " + mOriginalHeaderX + " , " + mOriginalHeaderY);


        //X轴百分比
        float mPercentX = dependency.getX() / mOriginalHeaderX;
        if (mPercentX >= 1) {
            mPercentX = 1;
        }
        //Y轴百分比
        float mPercentY = dependency.getY() / mOriginalHeaderY;
        if (mPercentY >= 1) {
            mPercentY = 1;
        }

//        LogUtils.e("Percent X,Y >> " + mPercentX + " , " + mPercentY);


        float x = mOriginalHeaderX - mOriginalHeaderX * mPercentX;
        if (x <= child.getWidth()) {
            x = child.getWidth() / 2;
        }

        float y = mOriginalHeaderY - mOriginalHeaderY * mPercentY;
        // TODO 头像的放大和缩小没做

        child.setX(x);
        child.setY(y);
//        child.setX(168);
//        child.setY(0);

        LogUtils.e("X,Y >> " + x + " , " + y);


        if (y >= 0) {
            RxBus.getInstance().post(y);
        }


//        if (deltaY == 0) {
//            deltaY = dependency.getY() - child.getHeight();
//        }
//
//        float dy = dependency.getY() - child.getHeight();
//        dy = dy < 0 ? 0 : dy;
////        float y = -(dy / deltaY) * child.getHeight();
//        float y = (dy / deltaY) * child.getHeight();
//        child.setTranslationY(y);
//
//        LogUtils.e(" Y: " + y);


        return true;
    }
}